<template>
  <div>
    <el-form inline :model="lostItemQuery" ref="queryFormRef">
      <el-form-item prop="keywords">
        <el-input v-model="lostItemQuery.keywords" placeholder="关键字"></el-input>
      </el-form-item>
      <el-form-item prop="keywords">
        <el-select v-model="lostItemQuery.status" placeholder="状态" style="width: 240px">
          <el-option label="全部" :value="-1"></el-option>
          <el-option label="未完成" :value="0"></el-option>
          <el-option label="已完成" :value="1"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button :icon="Search" @click="getLostItemPage">查询</el-button>
      </el-form-item>
      <el-form-item>
        <el-button :icon="Refresh" @click="queryFormRef?.resetFields()">重置</el-button>
      </el-form-item>
    </el-form>
    <el-button :icon="Plus" type="primary" @click="dialogVisible = true" size="small"
    >新增
    </el-button>
    <el-table :data="lostItemPage.list" style="width: 100%" v-loading="loading">
      <el-table-column prop="itemImageUrl" label="默认图片">
        <template #default="scope">
          <el-icon size="50">
            <el-image :src="scope.row.defaultPicture"/>
          </el-icon>
        </template>
      </el-table-column>
      <el-table-column prop="lostItemId" label="失物ID"></el-table-column>
      <el-table-column prop="userId" label="发布者"></el-table-column>
      <el-table-column prop="itemName" label="失物名称"></el-table-column>
      <el-table-column prop="description" label="描述"></el-table-column>
      <el-table-column prop="lostLocation" label="丢失地点"></el-table-column>
      <el-table-column prop="schoolId" label="学校id"></el-table-column>
      <el-table-column prop="lostTime" label="丢失时间">
        <template #default="scope">
          {{ scope.row.lostTime ? scope.row.lostTime.toLocaleString() : '' }}
        </template>
      </el-table-column>
      <el-table-column prop="status" label="状态">
        <template #default="scope">
          {{ scope.row.status === 0 ? '丢失' : '找回' }}
        </template>
      </el-table-column>
      <el-table-column prop="createTime" label="创建时间">
        <template #default="scope">
          {{ scope.row.createTime ? scope.row.createTime.toLocaleString() : '' }}
        </template>
      </el-table-column>
      <el-table-column prop="updateTime" label="修改时间">
        <template #default="scope">
          {{ scope.row.updateTime ? scope.row.updateTime.toLocaleString() : '' }}
        </template>
      </el-table-column>
      <el-table-column prop="remark" label="备注"></el-table-column>
      <el-table-column label="操作" width="250">
        <template #default="scope">
          <el-button type="primary" @click="openUpdate(scope.row.lostItemId)" size="small">修改</el-button>
          <el-divider direction="vertical"></el-divider>
          <el-button type="danger" @click="openDel(scope.row.lostItemId)" size="small">删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    <div>
      <el-pagination
          v-model:current-page="lostItemQuery.pageNum"
          v-model:page-size="lostItemQuery.pageSize"
          :total="lostItemPage.total"
          layout="prev, pager, next"
      >
      </el-pagination>
    </div>
    <el-dialog
        v-model="dialogVisible"
        :title="isAdd ? '新增':'修改'"
        width="800"
        @close="resetLostItemForm"
    >
      <el-form :model="lostItemsForm" inline label-width="120px" ref="lostItemsFormRef">
        <el-form-item label="默认图片">
          <el-upload
              class="avatar-uploader"
              action="/api/file/upload/serve/lost-found"
              :show-file-list="false"
              :on-success="handleAvatarSuccess"
          >
            <img v-if="lostItemsForm.defaultPicture" :src="lostItemsForm.defaultPicture" class="avatar" alt=""/>
            <el-icon v-else class="avatar-uploader-icon">
              <Plus/>
            </el-icon>
          </el-upload>
        </el-form-item>
        <el-form-item label="发布者">
          <el-input v-model="lostItemsForm.userId"></el-input>
        </el-form-item>
        <el-form-item label="失物名称">
          <el-input v-model="lostItemsForm.itemName"></el-input>
        </el-form-item>
        <el-form-item label="分类">
          <el-select
              v-model="lostItemsForm.lostFoundCategoryId"
              placeholder="Select"
              size="large"
              style="width: 240px"
              @focus="getLostFoundCategoryList"
          >
            <el-option
                v-for="item in lostFoundCategoryList"
                :key="item.lostFoundCategoryId"
                :label="item.name"
                :value="item.lostFoundCategoryId"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="学校编号">
          <el-input v-model="lostItemsForm.schoolId"></el-input>
        </el-form-item>
        <el-form-item label="丢失地点">
          <el-input v-model="lostItemsForm.lostLocation"></el-input>
        </el-form-item>
        <el-form-item label="丢失时间">
          <el-date-picker
              v-model="lostItemsForm.lostTime"
              type="datetime"
              placeholder="选择日期时间">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="状态">
          <el-select v-model="lostItemsForm.status" placeholder="请选择状态" style="width: 240px">
            <el-option label="丢失" value="0"></el-option>
            <el-option label="找回" value="1"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="创建时间">
          <el-date-picker
              v-model="lostItemsForm.createTime"
              type="datetime"
              placeholder="选择日期时间">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="修改时间">
          <el-date-picker
              v-model="lostItemsForm.updateTime"
              type="datetime"
              placeholder="选择日期时间">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="描述">
          <el-input v-model="lostItemsForm.description" type="textarea"></el-input>
        </el-form-item>
        <el-form-item label="备注">
          <el-input v-model="lostItemsForm.remark" type="textarea"></el-input>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="submitLostForm(lostItemsFormRef)">
            提交
          </el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import {onMounted, reactive, ref, watch} from "vue";
import {Search, Refresh, Plus} from "@element-plus/icons-vue";
import {
  reqGetLostItemPage,
  reqAddLostItem,
  reqUpdateLostItem,
  reqDeleteLostItem,
  reqGetLostItemById, reqGetLostFoundCategoryList
} from "@/api/serve/lost";
import type {LostItems} from "@/api/serve/lost/type";
import type {FormInstance} from "element-plus";
import {ElMessage, ElMessageBox} from "element-plus";
import {LostFoundCategory} from "@/api/serve/lost/type";

let lostItemQuery = reactive({
  keywords: "",
  status: -1,
  pageNum: 1,
  pageSize: 7
})
let lostItemPage = reactive({
  total: 0,
  list: [],
  pageNum: 1,
})
let lostFoundCategoryList = ref<LostFoundCategory[]>([])
let queryFormRef = ref<FormInstance>()
let lostItemsFormRef = ref<FormInstance>()
let loading = ref(true)
let isAdd = ref(true)
let dialogVisible = ref(false)
let lostItemsForm = reactive<LostItems>({
  lostItemId: "",
  userId: "",
  itemName: "",
  description: "",
  lostLocation: "",
  lostTime: null,
  defaultPicture: "",
  status: 0,
  createTime: null,
  updateTime: null,
  remark: "",
  schoolId: ""
});

let resetLostItemForm = () => {
  Object.assign(lostItemsForm, {
    lostItemId: "",
    userId: "",
    itemName: "",
    description: "",
    lostLocation: "",
    lostTime: null,
    defaultPicture: "",
    status: 0,
    createTime: null,
    updateTime: null,
    remark: "",
    schoolId: ""
  })
}
let getLostItemPage = () => {
  reqGetLostItemPage(lostItemQuery).then((res) => {
    Object.assign(lostItemPage, res.data)
    loading.value = false
  })
}
let openUpdate = (lostItemId: string) => {
  reqGetLostItemById(lostItemId).then((res) => {
    getLostFoundCategoryList()
    Object.assign(lostItemsForm, res.data)
    dialogVisible.value = true
    isAdd.value = false
  })
}
let getLostFoundCategoryList = () => {
  reqGetLostFoundCategoryList().then((res) => {
    lostFoundCategoryList.value = res.data
  })
}
let handleAvatarSuccess = (res) => {
  lostItemsForm.defaultPicture = res.data
}
let submitLostForm = async (formEl: FormInstance | undefined) => {
  if (!formEl) return;
  await formEl.validate(async (valid, fields) => {
    if (valid) {
      if (isAdd.value) {
        await reqAddLostItem(lostItemsForm);
      } else {
        await reqUpdateLostItem(lostItemsForm);
        isAdd.value = true;
      }
      await getLostItemPage();
      dialogVisible.value = false;
    } else console.log("error submit!", fields);
  });
}
let openDel = (lostItemId: string) => {
  ElMessageBox.confirm("删除之后不能恢复，确认删除吗？", "警告", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
  })
      .then(() => {
        reqDeleteLostItem(lostItemId).then(() => {
          getLostItemPage();
          ElMessage({
            message: "删除成功！",
            type: "success",
          });
        });
      })
      .catch(() => {
        ElMessage({
          type: "info",
          message: "取消删除！",
        });
      });
};
onMounted(() => {
  getLostItemPage()
})
watch([() => lostItemQuery.pageNum, () => lostItemQuery.pageSize], () => {
  getLostItemPage()
})
</script>
<style scoped>
.avatar-uploader .avatar {
  width: 178px;
  height: 178px;
  display: block;
}
</style>
<style>
.avatar-uploader .el-upload {
  border: 1px dashed var(--el-border-color);
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  transition: var(--el-transition-duration-fast);
}

.avatar-uploader .el-upload:hover {
  border-color: var(--el-color-primary);
}

.el-icon.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  text-align: center;
}
</style>
